import requests
import json,csv
from datetime import datetime
from enum import Enum
import copy
import os,time
import pandas as pd
from multiprocessing import Pool, Lock, current_process
import sqlite3

class People(Enum):
	man = 1
	woman = 2

time_out = 18
retry = 18
cpucore = 10

def init(l):
	global lock
	lock = l
	
def my_print(*args, **kwargs):
	kwargs['flush'] = True
	print(*args, **kwargs)

def httpOpt_session_with_lock(req, ses):
	i = 0
	#time_out = 16
	#retry = 4
	global time_out
	global retry
	while i < retry:
		try:
			url, headersList, bodydict, method = req.get('url'), req.get('headersList'), req.get('payload'), req.get('method')
			res = ses.request(method, url, data=json.dumps(bodydict), headers=headersList, timeout=time_out)
			if res.status_code == 200:
				return res
			else:
				i += 1
				time_out = 16 + i*8
				res.close()
				time.sleep(i)
				with lock:
					timer = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
					my_print(f"PID: {current_process().pid:5d} {timer} {i:2d} {time_out:3d} httpOpt status_code At: {res.status_code} {url}")
		except Exception as err:
			i += 1
			time_out = 16 + i*8
			time.sleep(i)
			with lock:
				timer = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
				my_print(f"PID: {current_process().pid:5d} {timer} {i:2d} {time_out:3d} httpOpt func err: {err} {url}")
	return False
	
def httpOpt_session_no_lock(req, ses):
	i = 0
	#time_out = 16
	#retry = 4
	global time_out
	global retry
	while i < retry:
		try:
			url, headersList, bodydict, method = req.get('url'), req.get('headersList'), req.get('payload'), req.get('method')
			res = ses.request(method, url, data=json.dumps(bodydict), headers=headersList, timeout=time_out)
			if res.status_code == 200:
				return res
			else:
				i += 1
				time_out = 16 + i*8
				res.close()
				time.sleep(i)
				timer = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
				my_print(f"{timer} {i:2d} {time_out:3d} httpOpt status_code At: {res.status_code} {url}")
		except Exception as err:
			i += 1
			time_out = 16 + i*8
			time.sleep(i)
			timer = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
			my_print(f"{timer} {i:2d} {time_out:3d} httpOpt func err: {err} {url}")
	return False

